package coller

import (
	"github.com/gin-gonic/gin"
	"math/rand"
	"model"
	"net/http"
	"pkg"
	"strconv"
	"time"
	"types"
)

// 用户注册
func UserAdd(c *gin.Context) {
	ClassId, _ := strconv.Atoi(c.PostForm("class_id"))
	Username := c.PostForm("username")
	Password := c.PostForm("password")
	Phone := c.PostForm("phone")
	Age, _ := strconv.Atoi(c.PostForm("age"))
	Sex, _ := strconv.Atoi(c.PostForm("sex"))
	i := rand.Intn(9000) + 1000
	pwd := pkg.Md5(Password + strconv.Itoa(i))
	pone := model.User{
		ClassId:  ClassId,
		Username: Username,
		Password: pwd,
		Phone:    Phone,
		Age:      Age,
		Sex:      Sex,
		Slat:     strconv.Itoa(i),
	}
	err := pone.UserAdd()
	if err != nil {
		c.JSON(http.StatusBadRequest, types.Router{
			Code: -1,
			Msg:  "注册失败",
			Data: nil,
		})
		return
	}

	c.JSON(http.StatusOK, types.Router{
		Code: 200,
		Msg:  "注册成功",
		Data: nil,
	})
}

// 用户登录
func UserLogin(c *gin.Context) {
	Username := c.PostForm("username")
	Password := c.PostForm("password")
	pone := model.User{Username: Username}
	res, err := pone.UserLogin()
	if err != nil {
		c.JSON(http.StatusBadRequest, types.Router{
			Code: -1,
			Msg:  "登录失败",
			Data: nil,
		})
		return
	}
	if pkg.Md5(Password+res.Slat) != res.Password {
		c.JSON(http.StatusBadRequest, types.Router{
			Code: -1,
			Msg:  "密码错误",
			Data: nil,
		})
		return
	}
	jwt, err := pkg.GetJwtToken("2204a", time.Now().Unix(), 86400, strconv.Itoa(int(res.ID)))
	if err != nil {
		c.JSON(http.StatusBadRequest, types.Router{
			Code: -1,
			Msg:  "登录失败",
			Data: nil,
		})
		return
	}
	c.JSON(http.StatusOK, types.Router{
		Code: 200,
		Msg:  "登录成功",
		Data: map[string]interface{}{
			"jwt": jwt,
		},
	})
}
